function League() {
    this.leagues = {
    /*  
        'name' : {
            'name' : '',                    // 名字
            'country' : '',                 // 所属国家{'wei','shu','wu'}
            'level' : 0,                    // 等级
            'xp' : 0,                       // 经验
            'leader' : 0,                   // 军团长
            'vice_leader' :[],              // 副团长
            'members' : {                   // 成员
                uid : {                     // 成员ID
                    'history_contribute':0, // 历史个人贡献
                    'time':0,               // 上次登陆时间
                }
            },
            'applying' : {
                uid:{
                    time: 0,
                }
            },                // 正在申请军团的列表
            'tech' : {                      // 科技
                'id':level 
            },                    
            'contribute' : 0,               // 即时军团贡献
            'notice' : '',                  // 公告 
            'introduce' :'',                // 介绍
            'log' : [],                     // 日志 
            'duplicate' : 0,                // 副本信息ID
        }
    */
    };

    this.logs = {               // 军团日志存储数组
        /*'name' : [{           // 军团名字
            'name':,            // 玩家名字
            'time':,                
            'cash' or 'activity'// 类型
        }]*/
    };

    this.users = {};            // 玩家所在军团
    this.applying = {};         // 玩家申请军团

    this.updates = {};
    this.saveCount = 0;
}

League.create = function() {
    gDBWorld.insert({_id:'league',  league :{} }, function(err, result){}); 
};

League.prototype = {

    init : function(callback) {
        // 读取排行榜数据
        gDBWorld.findOne({_id : 'league'}, {}, function(err, doc){
            if( doc ) {
                this.leagues = doc.league;
                this._init();
                callback && callback(true);
            }else{
                callback && callback(false);
            }
        }.bind(this));
    },

    _init : function(){
        var users = {};
        for( var name in this.leagues ) {
            var league = this.leagues[name];
            for( var uid in league.members ) {
                this.users[uid] = name;

                if( !(uid in users) ) {
                    users[uid] = [];
                }
                users[uid].push([name, uid == league.leader || league.vice_leader.indexOf(+uid) >= 0]);
            }
            for( var uid in league.applying ) {
                var userApplying = league.applying[uid];
                if( !userApplying.time ) {
                    userApplying = {'time': userApplying};
                    league.applying[uid] = userApplying;
                    this.markDirty(name, 'applying');
                }
                var applying = this.applying[uid] || {};
                applying[name] = userApplying.time;
                this.applying[uid] = applying;
            }

            for (var techId in league.tech) {
                var techLevel = +league.tech[techId];
                if (techLevel > gConfRuntime.LeagueTechMaxLevel) {
                    league.tech[techId] = gConfRuntime.LeagueTechMaxLevel;
                }
            }
        }

        for( var uid in users ) {
            var user = users[uid];
            if( user.length <= 1 ) continue;
            var league = '';
            for( var i=0; i<user.length; i++ ) {
                var data = user[i];
                if( !league || data[1] ) {
                    league = data[0];
                }
            }

            this.users[uid] = league;
            for( var i=0; i<user.length; i++ ) {
                var data = user[i];
                var otherLeague = data[0];
                if( otherLeague != league ) {
                    delete this.leagues[otherLeague].members[uid];
                    this.markDirty(otherLeague, 'members');
                }
            }
        }
        
        // 修正军团长,副军团长
        for( var name in this.leagues ) {
            var league = this.leagues[name];
            if( !(league.leader in league.members) ) {
                var uids = Object.keys(league.members);
                league.leader = + uids[0];
                this.markDirty(name, 'leader');
            }

            var haveInvalidVice = false;
            for( var i=0; i<league.vice_leader.length; i++ ) {
                var leader = league.vice_leader[i];
                if( !(leader in league.members) ) {
                    haveInvalidVice = true;
                }
            }
            if( haveInvalidVice ) {
                var validVice = [];
                for( var i=0; i<league.vice_leader.length; i++ ) {
                    var leader = league.vice_leader[i];
                    if( leader in league.members ) {
                        validVice.push(leader);
                    }
                }

                league.vice_leader = validVice;
                this.markDirty(name, 'vice_leader');
            }
        }
    },

    markDirty : function(name, attr) {
        // 标记军团脏数据
        var league = this.leagues[name];
        if( !league || !league.hasOwnProperty(attr) ) return;
        
        this.updates[util.format('league.%s.%s', name, attr)] = league[attr];
    },

    save : function(force, callback) {
        this.saveCount += 1;

        if( !force && this.saveCount < 100 ) {
            callback && callback(true);
            return;
        }
        
        var updates = this.updates;
        this.updates = {};
        this.saveCount = 0;

        gDBWorld.update({_id : 'league'}, {$set:updates}, function(err, result){
            if( err ) {
                ERROR(util.format('SAVE LEAGUE: %j %j', updates, err));
                callback && callback(false);
            }else {
                LOG(util.format('SAVE LEAGUE: %j', updates));
                callback && callback(true);
            }
        });
    },

    addLog : function(name, log) {
        var logs = this.logs[name];
        if( !logs ) {
            logs = [];
            this.logs[name] = logs;
        }

        if( logs.length >= 30 ) {
            logs.shift(); 
        }

        logs.push(log);
    },

    create : function(name, uid, country) {
        var league = {
            'name' : name,
            'country' : country,
            'level' : 1,
            'xp' : 0,
            'leader' : +uid,
            'vice_leader' :[],
            'members' : {},
            'applying' : {},
            'tech' : {},
            'contribute' : 0,
            'notice' : '',
            'introduce' :'',
            'log' : [],
            'duplicate' : 0,
        }

        this.leagues[name] = league; 

        this.addMember(name, uid); 

        for( var attr in league ) {
            this.markDirty(name, attr);
        }
    },

    apply : function(name, uid) {
        var league = this.leagues[name];
        if( !league ) return;
        
        var now = common.getTime();
        league.applying[uid] = {'time': now};
        var applying = this.applying[uid] || {};
        applying[name] = now;
        this.applying[uid] = applying;

        this.markDirty(name, 'applying');

        return applying;
    },

    cancelApply : function(name, uid) {
        var applying = this.applying[uid] || {};
        delete applying[name];

        var league = this.leagues[name];
        if( league ) {
            delete league.applying[uid];
            this.markDirty(name, 'applying');
        }

        return applying;
    },

    denyApply : function(name, uid) {
        var league = this.leagues[name];
        if( !league ) return;

        if( !uid ) {
            // 所有
            for( var applyUid in league.applying ) {
                delete this.applying[applyUid][name];
            }
            league.applying = {};
        }else {
            if( !league.applying[uid] ) return;
            delete league.applying[uid];
            delete this.applying[uid][name];
        }

        this.markDirty(name, 'applying');
    },

    addMember : function(name, uid) {
        var league = this.leagues[name];
        if( Object.keys(league.members).length >= gConfLeagueLevel[league.level].UserNum ) {
            return null;
        }

        var member = {
            'history_contribute' : 0,  
            'time': common.getTime(),
        };

        this.leagues[name].members[uid] = member; 
        this.users[uid] = name;
        this.markDirty(name, 'members');
        this.removeApplying(uid);

        return member;
    },

    removeMember : function(name, uid) {
        var league = this.leagues[name];
        if( !league ) return false;

        var members = league.members;
        if( !members[uid] ) return false;

        if( league.leader == uid ) return false;

        delete members[uid];
        delete this.users[uid];

        this.markDirty(name, 'members');

        this.dismissViceLeader(name, uid);

        gMessage.resetLeaguetalk(uid); 

        if (league.duplicate) {
            gLeagueDuplicate.removeMember(league.duplicate, uid);
        }

        return true;
    },

    removeApplying : function(uid) {
        var applying = this.applying[uid];
        if( !applying ) return;

        for( var leagueName in applying ) {
            delete this.leagues[leagueName].applying[uid];
            this.markDirty(leagueName, 'applying')
        }

        delete this.applying[uid];
    },

    getApplying : function(uid) {
        return this.applying[uid] || {};
    },

    getUserLeague : function(uid) {
        var name = this.users[uid];
        if( !name ) return null;

        return this.leagues[name];
    },

    getLeagueByName : function(leagueName) {
        return this.leagues[leagueName];
    },

    getLeagueDuplicate : function(league) {
        if (!league || league.level < 4) {
            return null;
        }

        if (!league.duplicate || !gLeagueDuplicate.get(league.duplicate)) {
            league.duplicate = gLeagueDuplicate.add();
            this.markDirty(league.name, 'duplicate');
            gLeague.save(true);
        }

        return gLeagueDuplicate.get(league.duplicate);
    },
        
    dismissViceLeader : function(name, uid) {
        var viceLeader = this.leagues[name].vice_leader;
        var index = viceLeader.indexOf(uid);
        if( index < 0 ) {
            return false;
        }

        viceLeader.splice(index, 1);
        this.markDirty(name, 'vice_leader');
        return true;
    },

    promoteViceLeader : function(name, uid) {
        var viceLeader = this.leagues[name].vice_leader;
        if( viceLeader.indexOf(uid) >= 0 ) return;

        viceLeader.push(uid);
        this.markDirty(name, 'vice_leader');
    },

    isLeaderGroup : function(name, uid) {
        var league = this.leagues[name];
        if( !league ) return false;

        return (league.leader == uid) || (league.vice_leader.indexOf(uid) >= 0);
    },

    isLeagueLeader : function(league, uid) {
        if (!league) {
            return false;
        }

        return (league.leader == uid) || (league.vice_leader.indexOf(uid) >= 0);
    },

    login : function(name, uid) {
        var league = this.leagues[name];
        if( !league ) return;
        var member = league.members[uid];
        if( !member ) return;

        member.time = common.getTime();
        this.markDirty(name, 'members');
    },

    checkApplyingTime : function() {
        var now = common.getTime();
        for( var name in this.leagues ) {
            var applying = this.leagues[name].applying; 
            for( var uid in applying ) {
                if( (now - applying[uid].time) > 86400 ) {
                    delete applying[uid];
                    delete this.applying[uid][name];
                    this.markDirty(name, 'applying');
                }
            }
        }
    },

    getRetLeague: function(name, full) {
        var league = this.leagues[name]; 
        var retLeague = {
            'name' : name,
            'country' : league.country,
            'level' : league.level,
            'xp' : league.xp,
            'leader' : league.leader,
            'vice_leader' :league.vice_leader,
            'members' : {},
            'contribute' : league.contribute,
            'introduce' :league.introduce,
        };


        var maxDuplicate = 0;
        if (league.duplicate) {
            var leagueDuplicate = gLeagueDuplicate.get(league.duplicate);
            if (leagueDuplicate) {
                maxDuplicate = leagueDuplicate.max;
            }
        }
        retLeague.duplicate_max = maxDuplicate;
        
        var rankUsers = gRank.users; 
        var members = league.members; 
        var retMembers = retLeague.members;
        for( var id in members ) {
            var member = members[id];
            var userInfo = gUserInfo.getUser(id);
            retMembers[id] = {
                'name' : userInfo.name,
                'headpic' : userInfo.headpic,
                'level' : userInfo.level,
                'rank' : rankUsers[id] || 0,
                'history_contribute' : member.history_contribute,
                'time' : member.time,
            } 
        } 
        
        if( full ) {
            var retApplying = {}; 
            var applying = league.applying; 
            for( var id in applying ) {
                if( !(id in rankUsers) ) {
                     continue; 
                }  
                
                var userInfo = gUserInfo.getUser(id);
                retApplying[id] = {
                    'name' : userInfo.name, 
                    'headpic': userInfo.headpic,
                    'level' : userInfo.level,
                    'rank' : rankUsers[id],
                    'time' :  applying[id].time, 
                };
            }

            retLeague.applying = retApplying; 
            retLeague.log = this.logs[name] || [];
            retLeague.tech = league.tech;
            retLeague.notice = league.notice;
        }
        
        return retLeague;
    },

    getLeagueList : function(leagueNameArr) {
        if( !leagueNameArr ) {
            leagueNameArr = Object.keys(this.leagues);
        }

        var leagueArr = []; 
        for(var i = 0,len = leagueNameArr.length; i < len; i++) {
            var name = leagueNameArr[i];
            var league = this.leagues[name]; 
            if( !league ) {
                continue; 
            }
            
            var fightForceSum = 0;
            for( var id in league.members ) {
                fightForceSum += gUserInfo.getUser(id).fight_force;
            }

            var maxDuplicate = 0;
            if (league.duplicate) {
                var leagueDuplicate = gLeagueDuplicate.get(league.duplicate);
                if (leagueDuplicate) {
                    maxDuplicate = leagueDuplicate.max;
                }
            }

            var retLeague = {
                'name' : name,
                'country' : league.country,
                'level' : league.level,
                'leader' : league.leader,
                'leader_name' : gUserInfo.getUser(league.leader).name,
                'member_num': Object.keys(league.members).length,
                'fight_force' : fightForceSum,
                'duplicate_max' : maxDuplicate,
            };
 
            leagueArr.push(retLeague);
        }

        return leagueArr;
    },
};

exports.create = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        var name =  req.args.name; 
        var country = req.args.country;

        var now = common.getTime();
        
        var league = gLeague.getUserLeague(uid);
        if( league ) {
            resp.data.update = 1;
            break;
        }

        if( name in gLeague.leagues ) {
            resp.data.exited = 1; 
            break;
        }

        gLeague.create(name, uid, country);
         
        resp.data.league = gLeague.getRetLeague(name, true);
    }while(false);
    
    gLeague.save(); 
    onHandled();

}

exports.get = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        if( !(uid in gRank.users) ) {
            resp.data.norank = 1; break;
        }

        if( req.args.list ) {
            resp.data.leaguearr = gLeague.getLeagueList();
        }else{
            var league = gLeague.getUserLeague(uid);
            if( !league ) {
                resp.data.leaguearr = gLeague.getLeagueList();
                resp.data.applying = gLeague.getApplying(uid);
                break;
            }else{
                var leagueName = league.name;
                resp.data.registered = gLeagueWar.isRegistered(leagueName) ? 1:0;
                resp.data.league = gLeague.getRetLeague(leagueName, true); 
            }
        }
    } while(false);

    // 是否领取军团战的奖励
    if( gLeagueWar.haveReward(uid) ) {
        resp.data.have_reward = 1;
    }

    gLeague.save();
    onHandled();
}

exports.get_applying = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        var league = gLeague.getUserLeague(uid);
        if( league ) {
            resp.data.update = 1;
            break;
        }

        resp.data.applying = gLeague.getApplying(uid);
        resp.data.leaguearr = gLeague.getLeagueList(Object.keys(resp.data.applying));
    }while(false);
    
    onHandled();
}

exports.apply = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        var league = gLeague.getUserLeague(uid);
        if( league ) {
            resp.data.update = 1;
            break;
        }

        var applying = gLeague.getApplying(uid);
        if( Object.keys(applying).length >= 3 ) {
            resp.data.update = 1;
            break;
        }

        applying = gLeague.apply(req.args.name, uid);
        resp.data.applying = applying;
    }while(false);
    
    gLeague.save();
    onHandled();
}

exports.cancel_apply = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        var league = gLeague.getUserLeague(uid);
        if( league ) {
            resp.data.update = 1;
            break;
        }else{
            resp.data.applying = gLeague.cancelApply(req.args.name, uid);
        }
    }while(false);

    gLeague.save();
    onHandled();
}

exports.handle_apply = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.data.update = 1; break;
        }

        if( !gLeague.isLeaderGroup(league.name, uid) ) {
            resp.data.update = 1; break;
        }
        
        if( req.args.all ) {
            // 拒绝所有
            gLeague.denyApply(league.name);
            break;
        }

        if( isNaN(req.args.id) ) {
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var targetId = +req.args.id;
        if( !(targetId in league.applying) ) {
            resp.data.update = 1; break;
        }

        if( req.args.agree ) {
            var member = gLeague.addMember(league.name, targetId) 
            if( !member ) {
                resp.data.full = 1; break;
            }
            
            var userInfo = gUserInfo.getUser(targetId);
            resp.data.member = {
                'history_contribute' : member.history_contribute,
                'time' : member.time,
                'name' : userInfo.name,
                'level': userInfo.level,
                'headpic': userInfo.headpic,
                'rank' : userInfo.rank,
            };
        }else {
            gLeague.denyApply(league.name, targetId);
        }
    }while(false);
        
    gLeague.save();
    onHandled();
}

exports.set_notice = function(req, resp, onHandled) {

    var uid = req.uid;
    do {
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.data.update = 1; break;
        }

        if( !gLeague.isLeaderGroup(league.name, uid) ) {
            resp.data.update = 1; break;
        }

        if( req.args.introduce.length > 40 || req.args.notice.length > 40 ) {
            resp.code = 1; resp.desc = 'too much words'; break;
        }

        league.introduce = req.args.introduce;
        league.notice = req.args.notice;
        
        gLeague.markDirty(league.name, 'introduce');
        gLeague.markDirty(league.name, 'notice');

   }while(false);

    gLeague.save();
    onHandled();

}

exports.promote = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        if( isNaN(req.args.id) ) {
            resp.code = 1; resp.desc = 'no valid args'; break;
        }
        
        var id = +req.args.id;
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.data.update = 1; break;
        }

        if( league.leader != uid ) {
            resp.code = 1;  resp.desc = 'not enough root'; break;
        }

        var viceLeader = league.vice_leader; 
        if( viceLeader.length >= 2) {
            resp.code = 1; resp.desc = 'vice leader num over'; break;
        }

        if( !(id in league.members) ) {
            resp.data.update = 1; break;
        }

        gLeague.promoteViceLeader(league.name, id);

    }while(false);

    gLeague.save();
    onHandled();
}

exports.dismiss = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        if( isNaN(req.args.id) ) {
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var id = +req.args.id;
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.data.update = 1; break;
        }

        if( league.leader != uid ) {
            resp.code = 1;  resp.desc = 'not enough root'; break;
        }
        
        if( league.vice_leader.indexOf(id) < 0  ) {
            resp.data.update = 1; break;
        }

        gLeague.dismissViceLeader(league.name, id);
    }while(false);

    gLeague.save();
    onHandled();
}

exports.fire = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        if( isNaN(req.args.id) ) {
            resp.code = 1; resp.desc = 'no valid args'; break;
        }
        var id = +req.args.id;

        if( gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'under war'; break;
        }
        
        if( gLeagueBoss.isUnderBoss() ) {
            resp.code = 1; resp.desc = 'under boss'; break;
        }
        
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.data.update = 1; break;
        }

        if( league.leader == id || uid == id ) {
            resp.code = 1; resp.desc = 'id error'; break;
        }

        if( !gLeague.isLeaderGroup(league.name, uid) ) {
            resp.data.update = 1; break;
        }

        gLeague.removeMember(league.name, id);
    }while(false);

    gLeague.save();
    onHandled();
}

exports.transfer = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        if( isNaN(req.args.id) ) {
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var id = +req.args.id;
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.data.update = 1; break;
        }

        if( league.leader != uid ) {
            resp.data.update = 1; break;
        }

        if( league.vice_leader.indexOf(id) < 0 ) {
            resp.data.update = 1; break;
        }

        league.leader = id; 
        gLeague.dismissViceLeader(league.name, id);

        gLeague.markDirty(league.name, 'leader');
        gLeague.markDirty(league.name, 'vice_leader');

    }while(false);

    gLeague.save();
    onHandled();
}

exports.impeach = function(req, resp, onHandled) {
    var uid = req.uid;
    do {
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.data.update = 1; break; 
        }
        
        if( !(uid in league.members) ) {
            resp.data.update = 1; break; 
        }

        var now = common.getTime();
        if( now - league.members[league.leader].time < (86400*7) ) {
            resp.code = 1; resp.desc = 'time not reach'; break; 
        }

        gLeague.dismissViceLeader(league.name, uid);

        league.leader = uid;
        gLeague.markDirty(league.name, 'leader');

    } while(false);

    gLeague.save();
    onHandled();
}

exports.search= function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        var name = req.args.name;
        resp.data.leaguearr = gLeague.getLeagueList([name]);

    }while(false);

    onHandled();
}

exports.view_league = function(req, resp, onHandled) {
    var uid = req.uid;
    do {
        var name = req.args.name;
        
        if( !(name in gLeague.leagues) ) {
            resp.code = 1; resp.desc = 'invalid name'; break;
        }
        
        resp.data.league = gLeague.getRetLeague(name, false);

    }while(false);

    onHandled();
}

exports.contribute = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.data.update = 1; break;
        }
       
       if( isNaN(req.args.cash) || +req.args.cash < 1) {
            resp.code = 1; resp.desc = 'no valid args'; break;
        }
        
        var cash = Math.round(req.args.cash);
        var addContribute = gConfGlobal.LeagueContributePerCash * cash;

        var userData = league.members[uid];
        league.contribute += addContribute; 
        gLeague.markDirty(league.name, 'contribute');

        userData.history_contribute += addContribute;
        gLeague.markDirty(league.name, 'history_contribute');

        gLeague.addLog(league.name, {'name': gUserInfo.getUser(uid).name, 'time' : common.getTime(), 'cash' : cash}); 
        
        resp.data.contribute = addContribute; 
    } while(false);
    
    gLeague.save(); 
    onHandled();
}

exports.exit = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        if( gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'under war'; break;
        }

        if( gLeagueBoss.isUnderBoss() ) {
            resp.code = 1; resp.desc = 'under boss'; break;
        }

        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.data.update = 1; break; 
        }

        if( league.leader == uid ) {
            resp.data.update = 1; break; 
        }

        gLeague.removeMember(league.name, uid);

    }while(false);

    gLeague.save();
    onHandled();
}

exports.upgrade_tech = function(req, resp, onHandled) {

    var uid = req.uid;
    do {
        if( isNaN(req.args.id) ) {
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var id = +req.args.id;
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.data.update = 1; break;
        }

        if( !gLeague.isLeaderGroup(league.name, uid) ) {
            resp.data.update = 1; break;
        }

        var tech = league.tech;
        var newLevel = 1;
        if( tech[id] ) {
            newLevel = tech[id] + 1; 
        }

        var leagueTechConf = gConfLeagueTech[id][newLevel];
        if( !leagueTechConf ) {
            resp.code = 1; resp.desc = 'level to max'; break;
        }
        
        if( league.level < leagueTechConf.LeagueLevel ) {
            resp.code = 1; resp.desc = 'league level not match'; break;
        }
        
        var costContribute = leagueTechConf.Contribute;
        if( league.contribute < costContribute ) {
            resp.code = 1; resp.desc = 'not enough contribute'; break;
        }

        league.contribute += -costContribute; 
        tech[id] = newLevel;

        gLeague.markDirty(league.name, 'contribute');
        gLeague.markDirty(league.name, 'tech');

        resp.data.contribute = -costContribute;
        
    }while(false);

    gLeague.save();
    onHandled();
}

exports.upgrade_league = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        if( isNaN(req.args.contribute) || isNaN(req.args.xp) ) {
            resp.code = 1; resp.desc = 'no valid args'; break;
        }

        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.data.update = 1; break;
        }
        
        var addContribute = +req.args.contribute;
        var userData = league.members[uid];
        league.contribute += addContribute; 
        gLeague.markDirty(league.name, 'contribute');

        userData.history_contribute += addContribute;
        gLeague.markDirty(league.name, 'members');

        gLeague.addLog(league.name, {'name': gUserInfo.getUser(uid).name, 'time' : common.getTime(),
            'activity' : addContribute / gConfGlobal.LeagueContributePerActivity}); 

        if( league.level < 10 ) {
            league.xp += +req.args.xp; 
            gLeague.markDirty(league.name, 'xp');
            var oldLevel = league.level;
            var level = 1;
            for( level = 1; level < 100; level++ ) {
                if( !gConfLeagueLevel[level] || gConfLeagueLevel[level].Xp > league.xp ) {
                    break;
                }
            }

            if( oldLevel != level ) {
                league.level = level;
                gLeague.markDirty(league.name, 'level');
                if( level >= 10 ) {
                    gMessage.addSystemMessage('league_upgrade', [league.name]);
                }
            }
        }
    }while(false);

    gLeague.save();
    onHandled();
}

exports.update_login = function(req, resp, onHandled) {
    
    var uid = req.uid;
    do {
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.data.update = 1; break;
        }

        gLeague.login(league.name, uid);
        
    }while(false);

    gLeague.save();
    onHandled();
}

exports.gm_change = function(req, resp, onHandled) {
    var leagueName = req.args.name;
    var changeType = req.args.type;
    var changeValue = req.args.value;

    do {
        if (!leagueName || !changeType || !changeValue) {
            resp.code = 1; resp.desc = 'invalid args'; break;
        }

        if(req.args.key != config.GMAuth) {
            resp.code = 1; resp.desc = 'invalid key'; break;
        }

        var league = gLeague.getLeagueByName(leagueName);
        if (!league) {
            resp.code = 1; resp.desc = 'invalid league name'; break;
        }

        if ("level" == changeType) {
            var level = parseInt(changeValue);
            league.level = level;
            gLeague.markDirty(league.name, 'level');
        } else if ("dplevel" == changeType) {
            var levelId = parseInt(changeValue);
            var duplicate = gLeague.getLeagueDuplicate(league);
            if (!duplicate) {
                resp.code = 1; resp.desc = 'duplicate unlock'; break;
            }

            var duplicateConf = gConfLeagueDuplicate[levelId];
            if (!duplicateConf) {
                resp.code = 1; resp.desc = 'invalid duplicate id'; break;
            }

            for (var count = levelId - duplicate.cur; count > 0; --count) {
                duplicate.hp = 0;
                gLeagueDuplicate.toNextLevel(league, duplicate);
                gLeagueDuplicate.save(true);
            }
        } else {
            resp.code = 1; resp.desc = 'type not support'; break;
        }
    } while (false);

    onHandled && onHandled();
}

exports.League = League;
